/**
 * @name: axios.ts
 * @author: XU>.<CHEN
 * @date: 2022-02-27 16:37
 * @description：请求封装
 * @update: 2022-02-27 16:37
 */
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'

const http = axios.create({
  timeout: 1000 * 120, // 2 minutes
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 封装的异常对象
 * @param message
 * @param code
 * @constructor
 */
class EipException {
  msg: string
  code: number
  constructor(msg: string, code: number) {
    this.msg = msg
    this.code = code
  }
}

/**
 * 请求拦截
 */
http.interceptors.request.use((config: any) => {
  config.headers['authorization'] = getToken() // 请求头带上token
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * get请求
 * @param url
 * @param params
 * @returns {Promise<any>}
 */
export function handleGet(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    http.get(url, {
      params: { ...params, _t: new Date().getTime() }
    }).then(response => {
      resolve(resolve(response.data))
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * post 请求
 * @param url
 * @param data
 * @returns {Promise<any>}
 */
export function handlePost(url: string, data = {}) {
  data = JSON.stringify(data)
  return new Promise((resolve, reject) => {
    http.post(url, data).then(response => {
      resolve(resolve(response.data))
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * delete 请求
 * @param url
 * @param data
 * @returns {Promise<any>}
 */
export function handleDel(url: string, data = {}) {
  data = JSON.stringify(data)
  return new Promise((resolve, reject) => {
    http.delete(url, data).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * put 请求
 * @param url
 * @param data
 * @returns {Promise<any>}
 */
export function handlePut(url: string, data = {}) {
  data = JSON.stringify(data)
  return new Promise((resolve, reject) => {
    http.put(url, data).then(response => {
      resolve(resolve(response.data))
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  const res = response.data
  // 异常拦截
  if (res && res.code !== 200 && res.code !== 'success') {
    // 错误信息统一在这里处理、页面代码只需要关系正常情况即可
    ElMessage({
      message: response.data.message || '服务器异常',
      type: 'error',
      duration: 5 * 1000
    })
    throw new EipException(response.data.message, response.data.code)
  } else {
    return res
  }
}, error => {
  if (error.message && error.message === 'Network Error') {
    ElMessage({
      message: `服务无法访问，请确定当前终端是否能够访问`,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  } else {
    ElMessage({
      message: '接口无法访问',
      type: 'error',
      duration: 5 * 1000
    })
  }
  return Promise.reject(error)
})

export default axios
